package com.yfunc.ibatis3.orm;

import java.util.ArrayList;

import org.apache.ibatis.builder.SqlSourceBuilder;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.MappedStatement.Builder;

public class Command {

	private MappedStatement ms;
	private Object parameter;

	public Command(MappedStatement mappedStatement, Object parameter) {
		this.ms = mappedStatement;
		this.parameter = parameter;
	}
	
	public <T> T getParameter(){
		return (T) parameter;
	}
	
	public MappedStatement getMappedStatement(){
		return ms;
	}
	
	// see: MapperBuilderAssistant
	public Builder newMappedStatementBuilder(SqlSource sqlSource) {

		Builder builder = new MappedStatement.Builder(
				ms.getConfiguration(), ms.getId(),
				sqlSource, ms.getSqlCommandType());

		builder.resource(ms.getResource());
		builder.fetchSize(ms.getFetchSize());
		builder.statementType(ms.getStatementType());
		builder.keyGenerator(ms.getKeyGenerator());
		// builder.keyProperty(ms.getk);

		// setStatementTimeout()
		builder.timeout(ms.getTimeout());

		// setStatementResultMap()
		builder.parameterMap(ms.getParameterMap());
		builder.resultMaps(ms.getResultMaps());
		builder.resultSetType(ms.getResultSetType());

		// setStatementCache()
		builder.cache(ms.getCache());
		builder.flushCacheRequired(ms.isFlushCacheRequired());
		builder.useCache(ms.isUseCache());
		return builder;
	}

	public SqlSource newSqlSource(String sql, Class entityClazz) {
		return new SqlSourceBuilder(ms.getConfiguration()).parse(sql, entityClazz, null);
	}
	
	public Builder newMappedStatementBuilder(String sql, Class entityClazz){
		return newMappedStatementBuilder(newSqlSource(sql, entityClazz));
	}
	
	public ResultMap newResultMap(Class<?> entityClass){
		return new ResultMap.Builder(ms.getConfiguration() , ms.getId() , entityClass ,  new ArrayList<ResultMapping>() , true).build();
	}
	
	
}
